package com.lmonkey.filter;

import com.lmonkey.dao.Basedao;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebFilter("/admin/admin_docatedel")
public class DocateDel implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest reqq = (HttpServletRequest)req;
        HttpServletResponse respp = (HttpServletResponse) resp;
        //设置字符集
        reqq.setCharacterEncoding("UTF-8");
        respp.setContentType("text/html;charset=utf-8");

        int id = Integer.parseInt(reqq.getParameter("id"));
        int count =0;

        Connection conn = Basedao.getconn();
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            String sql = "select count(*) from lmonkey_category where cate_parent_id = ? ";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            rs = ps.executeQuery();
            while(rs.next()){
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (count>0){
            PrintWriter out = respp.getWriter();
            out.println("<script>alert('该分类存在子分类，请先将子分类删除');location.href='/lyq/admin/admin_cateselect';</script>");
            out.close();
            return;
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
